package com.ygsoft.nio.fileserver;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;

public class ClientAcceptor extends Thread {
	
	private int port ;
	private SocketChannelQueue channelQueue ;
	//private LinkedBlockingQueue<SocketChannel> lbQueue = null;
	
	
	private ServerSocketChannel ssc ;
	private Selector acceptSelector ;
	
	public ClientAcceptor(SocketChannelQueue channelQueue, int port) throws IOException {
		this.port = port;
		this.channelQueue = channelQueue;
		
		this.acceptSelector = Selector.open();
		
		this.initServerSocket();
	}
	
	private void initServerSocket() throws IOException {
		this.ssc = ServerSocketChannel.open();
		this.ssc.configureBlocking(false);
		
		InetSocketAddress address = new InetSocketAddress(this.port);
		this.ssc.socket().bind(address);
		this.ssc.register(this.acceptSelector, SelectionKey.OP_ACCEPT);
	}
	
	public void run(){
		System.out.println("Active Accepter Thread..");
		try {
			while(true){
				int keys = this.acceptSelector.select();
				if(keys > 0){
					Iterator<SelectionKey> it = this.acceptSelector.selectedKeys().iterator();
					
					while(it.hasNext()){
						SelectionKey key = it.next();
						it.remove();
						
						ServerSocketChannel readyChannel = (ServerSocketChannel)key.channel();
						SocketChannel sockChannel = readyChannel.accept();
						
						System.out.println("Client Accepted ..");
						
						this.channelQueue.addLast(sockChannel);
					}
				}
			}
		} catch(IOException e){
			e.printStackTrace();
		} finally {
			try {
				ssc.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String ... v){
		
	}
}
